require('../../less/controls/list_view.less');
var React = require('react');
var ListViewItem = require('./ListViewItem');

module.exports = React.createClass({
	getDefaultProps: function () {
		return {
			autoLoad: true,
			singleSelect: true
		};
	},
	displayName: 'ListView',
	getInitialState: function(){
		return {
			currIndex: null,
			data: null
		}
	},
	componentDidMount:function(){
		var _autoLoad = this.props.autoLoad === undefined ? true : this.props.autoLoad;
		this._dataSource = Store.dataSource(this.props.data, {
			autoLoad: _autoLoad,
			onSuccess: function (data){
				this.__onDataLoaded(data.result?data.result:data);
			}.bind(this)
		});
	},
	refresh: function (){
		this._dataSource.refresh();
	},
	__onDataLoaded: function (data){
		this.state.data = data;
		this.setState({ data: data });
		if(this.props.fireIndex != undefined){
			this.fireClick(this.props.fireIndex);
		}
		this.props.onLoaded && this.props.onLoaded(data, this);
	},
	__onItemClick: function (event, item, index){
		this.props.singleSelect && this.setState({ currIndex: index });
		item.index = index;
		if(event){
			event.stopPropagation();
			event.preventDefault();
		}
		this.props.onClick && this.props.onClick(event, item);
	},
	fireClick: function (index){
		this.__onItemClick(null, this.state.data[index], index);
	},
	__itemRender: function (item, index){
		var _content = null;
		if(this.props.itemRender){
			_content = this.props.itemRender(item, index);
		}
		if(!_content){
			_content = <ListViewItem key={index} {...item} />
		}

		return <li key={index} className={this.state.currIndex==index?'curr':''} onClick={(event)=>this.__onItemClick(event, item, index)}>{_content}</li>;
	},
	render:function(){
		return (
			<ul className={"c-list-view " + (this.props.skin||'default') + " " + ((this.state.data||[]).length?'':'no-data')}>
				{
					this.state.data && this.state.data.map(this.__itemRender)
				}
			</ul>
		);
	}
});
